package main.com.cyz.Stack;

import java.util.Stack;

/**
 * @author fox
 * @version 1.0
 * @description 中缀表达式 转 后缀表达式
 * @date 2024/5/20 9:05
 */
public class InfixToSuffix {

    public String math(String infix){
        char[] chars = infix.toCharArray();
        Stack<Character> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        for (char aChar : chars) {
            switch (aChar){
                case '(':
                case '+':
                case '*':
                case '/':
                case '-':
                    extracted(stack, aChar, sb);
                    break;
                case ')':
                    while (stack.peek() != '('){
                        sb.append(stack.pop());
                    }
                    stack.pop();
                    break;
                default:
                    sb.append(aChar);
            }
        }
        while (!stack.isEmpty()){
            sb.append(stack.pop());
        }
        return sb.toString();
    }

    private void extracted(Stack<Character> stack, char aChar, StringBuilder sb) {
        if (stack.isEmpty() || priority(stack.peek()) < priority(aChar)){
            stack.push(aChar);
        }else{
            while (!stack.isEmpty() &&  priority(stack.peek()) >= priority(aChar)){
                sb.append(stack.pop());
            }
        }
    }

    private Integer priority(Character c){
        switch (c){
            case '(' : return 0;
            case '+' :
            case '-' :
                return 1;
            case '*' :
            case '/' :
                return 2;
            default: throw new RuntimeException("请输入基本运算字符");
        }
    }

}
